<template>
  <div class="task-dependencies-container">
    <div class="page-header">
      <div class="page-title">
        <el-button icon="el-icon-back" type="link" @click="goBack">返回</el-button>
        <h2>任务依赖关系</h2>
      </div>
      <el-button type="primary" @click="addDependency">添加依赖</el-button>
    </div>

    <el-card v-loading="loading">
      <div class="task-info" v-if="task">
        <h3>当前任务: {{ task.title }}</h3>
        <p>{{ task.description }}</p>
      </div>

      <el-tabs v-model="activeTab" type="border-card">
        <el-tab-pane label="依赖关系" name="dependencies">
          <el-empty v-if="!hasDependencies" description="暂无依赖关系"></el-empty>
          <el-table v-else :data="dependencies" style="width: 100%">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="dependent_task.title" label="当前任务" />
            <el-table-column prop="dependency_task.title" label="依赖任务" />
            <el-table-column prop="dependency_type" label="依赖类型">
              <template #default="scope">
                <el-tag :type="getDependencyTypeTag(scope.row.dependency_type)">
                  {{ getDependencyTypeText(scope.row.dependency_type) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button
                  type="danger"
                  size="small"
                  @click="removeDependency(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="依赖于此任务" name="dependents">
          <el-empty v-if="!hasDependents" description="暂无依赖此任务的任务"></el-empty>
          <el-table v-else :data="dependents" style="width: 100%">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="dependent_task.title" label="依赖此任务的任务" />
            <el-table-column prop="dependency_type" label="依赖类型">
              <template #default="scope">
                <el-tag :type="getDependencyTypeTag(scope.row.dependency_type)">
                  {{ getDependencyTypeText(scope.row.dependency_type) }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加依赖对话框 -->
    <el-dialog
      v-model="addDependencyDialogVisible"
      title="添加依赖"
      width="500px"
    >
      <el-form 
        ref="dependencyFormRef" 
        :model="dependencyForm" 
        :rules="dependencyRules"
        label-width="100px"
      >
        <el-form-item label="依赖任务" prop="dependencyTaskId">
          <el-select 
            v-model="dependencyForm.dependencyTaskId" 
            filterable 
            remote
            placeholder="请选择依赖任务"
            :remote-method="searchTasks"
            :loading="searching"
          >
            <el-option
              v-for="task in tasksOptions"
              :key="task.id"
              :label="task.title"
              :value="task.id"
            >
              <span style="float: left">{{ task.title }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                {{ task.project_name }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="依赖类型" prop="dependencyType">
          <el-select v-model="dependencyForm.dependencyType" placeholder="请选择依赖类型">
            <el-option label="强依赖" value="strong" />
            <el-option label="弱依赖" value="weak" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDependencyDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="submitDependency" 
          :loading="submitting"
        >
          确认
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'TaskDependencies',
  props: {
    id: {
      type: [String, Number],
      required: true
    }
  },
  setup(props) {
    const store = useStore()
    const route = useRoute()
    const router = useRouter()
    const dependencyFormRef = ref(null)

    // 数据状态
    const task = computed(() => store.state.currentTask)
    const loading = computed(() => store.getters.isLoading('taskDetail'))
    const dependencies = computed(() => {
      const deps = store.state.taskDependencies?.dependencies || []
      return deps
    })
    const dependents = computed(() => {
      const deps = store.state.taskDependencies?.dependents || []
      return deps
    })
    const hasDependencies = computed(() => dependencies.value.length > 0)
    const hasDependents = computed(() => dependents.value.length > 0)

    // UI状态
    const activeTab = ref('dependencies')
    const addDependencyDialogVisible = ref(false)
    const submitting = ref(false)
    const searching = ref(false)
    const tasksOptions = ref([])

    // 表单
    const dependencyForm = ref({
      dependencyTaskId: '',
      dependencyType: 'strong'
    })
    const dependencyRules = {
      dependencyTaskId: [
        { required: true, message: '请选择依赖任务', trigger: 'change' }
      ],
      dependencyType: [
        { required: true, message: '请选择依赖类型', trigger: 'change' }
      ]
    }

    // 获取任务详情和依赖关系
    const fetchData = async () => {
      // 获取任务详情
      await store.dispatch('fetchTaskDetail', props.id)
      // 获取任务依赖关系
      await store.dispatch('fetchTaskDependencies', props.id)
    }

    // 返回上一页
    const goBack = () => {
      router.back()
    }

    // 搜索任务
    const searchTasks = async (query) => {
      if (query) {
        searching.value = true
        // 模拟搜索任务的API调用
        // 实际项目中应该有一个搜索任务的API
        setTimeout(() => {
          tasksOptions.value = [
            { id: 101, title: `示例任务1 (${query})`, project_name: '项目1' },
            { id: 102, title: `示例任务2 (${query})`, project_name: '项目2' },
            { id: 103, title: `示例任务3 (${query})`, project_name: '项目3' }
          ]
          searching.value = false
        }, 1000)
      } else {
        tasksOptions.value = []
      }
    }

    // 显示添加依赖对话框
    const addDependency = () => {
      dependencyForm.value = {
        dependencyTaskId: '',
        dependencyType: 'strong'
      }
      addDependencyDialogVisible.value = true
    }

    // 提交依赖关系
    const submitDependency = async () => {
      if (!dependencyFormRef.value) return

      await dependencyFormRef.value.validate(async (valid) => {
        if (valid) {
          submitting.value = true
          try {
            await store.dispatch('addTaskDependency', {
              dependentTaskId: props.id,
              dependencyData: {
                dependency_task_id: dependencyForm.value.dependencyTaskId,
                dependency_type: dependencyForm.value.dependencyType
              }
            })
            ElMessage.success('依赖关系添加成功')
            addDependencyDialogVisible.value = false
          } catch (error) {
            ElMessage.error(`添加失败: ${error.message}`)
          } finally {
            submitting.value = false
          }
        }
      })
    }

    // 移除依赖关系
    const removeDependency = (dependency) => {
      ElMessageBox.confirm(
        '确定要删除此依赖关系吗？',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          await store.dispatch('removeTaskDependency', {
            dependencyId: dependency.id,
            taskId: props.id
          })
          ElMessage.success('依赖关系已删除')
        } catch (error) {
          ElMessage.error(`删除失败: ${error.message}`)
        }
      }).catch(() => {})
    }

    // 获取依赖类型标签和文本
    const getDependencyTypeTag = (type) => {
      switch (type) {
        case 'strong': return 'danger'
        case 'weak': return 'warning'
        default: return 'info'
      }
    }

    const getDependencyTypeText = (type) => {
      switch (type) {
        case 'strong': return '强依赖'
        case 'weak': return '弱依赖'
        default: return type
      }
    }

    onMounted(() => {
      fetchData()
    })

    return {
      task,
      loading,
      dependencies,
      dependents,
      hasDependencies,
      hasDependents,
      activeTab,
      addDependencyDialogVisible,
      dependencyForm,
      dependencyRules,
      dependencyFormRef,
      submitting,
      searching,
      tasksOptions,
      goBack,
      searchTasks,
      addDependency,
      submitDependency,
      removeDependency,
      getDependencyTypeTag,
      getDependencyTypeText
    }
  }
}
</script>

<style scoped>
.task-dependencies-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  display: flex;
  align-items: center;
}

.page-title h2 {
  margin: 0 0 0 10px;
}

.task-info {
  margin-bottom: 20px;
}

.task-info h3 {
  margin-top: 0;
}
</style> 